/**
  * Author: Mei
  * Date: 2020-11-22 16:51
  * Description: 
  *
  */
#include <queue>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <unistd.h>

struct response {
    static int &getCount() {
        static int theCount = 0;
        return theCount;
    }
    int id;
};
std::mutex mut;
std::condition_variable data_cond; //条件变量
std::queue<response> queue;

void produce() {
    for (int i = 0; i < 100; i++) {
        std::lock_guard<std::mutex> lk(mut);
        response r;
        r.id = response::getCount()++;
        queue.push(r);
        data_cond.notify_one();
        std::cout << "produced: " << r.id << std::endl;
    }
}
void consume() {
    int consumedCounter = 0;
    for (;;) {
        std::unique_lock<std::mutex> lk(mut);
        data_cond.wait(lk, []{return !queue.empty();});
        std::cout << "consumed: " << queue.front().id << std::endl;
        queue.pop();
        consumedCounter++;
        if (consumedCounter == 100)
            break;
    }
}

int main(int argc,char *argv[]) {

    std::thread t1(produce);
    std::thread t2(consume);

    t1.join();
    t2.join();

    return 0;
}